using Library.Domain;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ComponentModel.DataAnnotations;
using Core.Workflows;
using System.ComponentModel.DataAnnotations.Schema;
using Core.Factories;
using Core.Context;
using Core.Dtos;
using Library.Helpers;

namespace Core.Domain
{
    [DataContract]
    public class Policy : BaseEntity<int>
    {
        public Policy()
        {
        }

        [DataMember]
        public override int Id { get; set; }

        [Required]
        [DataMember]
        public long Number { get; set; }
                
        [DataMember]
        public int PersonID { get; set; }

        [Required]
        [Range(1, int.MaxValue, ErrorMessage = "The Field {0} is mandatory")]
        [DataMember]
        public int StateID { get; set; }

        [Required]
        [DataMember]
        public string UserID { get; set; }

        [Required]
        [DataMember]
        public System.DateTime DateCreated { get; set; }

        // Navigation properties		
        [DataMember]
        public virtual Person Person { get; set; }
        [DataMember]
        public virtual List<PolicyWFLog> WFLogs { get; set; }       

        [NotMapped]
        public ApprovalWorkflow Workflow { get; set; }
        
        private IWorkflowFactory workflowFactory;

        public void InitializeDependencies(IWorkflowFactory workflowFactory)
        {            
            this.workflowFactory = workflowFactory;
        }

        public void InstantiateWorkflow()
        {
            ApprovalState state = (ApprovalState)StateID;
            Workflow = workflowFactory.GetInstance(state);                        
        }

        public void SetInPending()
        {
            StateID = (byte)ApprovalState.Pending;
        }

        public IList<string> ComputeApprovalActions()
        {
            if (Workflow == null)
                return null;

            return EnumHelper<ApprovalAction>.ToListOfString(Workflow.PermittedTriggers);
        }

        public void DoAction(string actionName)
        {
            ApprovalAction action = EnumHelper<ApprovalAction>.ToEnum(actionName);                        
            Workflow.Fire(action);
            StateID = (byte)(Workflow.State);
            AddActionLog(action);
        }

        private void AddActionLog(ApprovalAction action)
        {
            if (WFLogs == null)
                WFLogs = new List<PolicyWFLog>();

            PolicyWFLog wfLog = new PolicyWFLog();
            wfLog.ActionID = (byte)action;
            wfLog.StateID = StateID;
            wfLog.UserID = UserID;
            wfLog.DateCreated = DateTime.Now;

            WFLogs.Add(wfLog);            
        }
    }
}


